package com.jt.provider.callback;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 自定义限流，熔断等异常处理器
 */
//@Component
public class SentinelBlockExceptionHandler  implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       BlockException e) throws Exception {
        //设置响应数据的编码
        response.setCharacterEncoding("utf-8");
        //告诉浏览器响应数据的类型以及编码(这个编码是浏览器呈现数据的编码)
        response.setContentType("text/html;charset=utf-8");
        //响应状态码
        response.setStatus(429);
        PrintWriter out = response.getWriter();
        if(e instanceof FlowException) {
            out.print("<h2>访问太频繁了,稍等片刻再访问</h2>");
        }else if(e instanceof DegradeException){
            out.print("<h2>服务维护中,稍等片刻再访问</h2>");
        }
        out.flush();
        out.close();
    }
}
